package org.example.menu.controller;

import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.lang.tree.TreeNodeConfig;
import cn.hutool.core.lang.tree.TreeUtil;
import cn.hutool.jwt.JWTUtil;
import org.example.menu.domain.Menu;
import org.example.menu.service.RoleMenuService;
import org.example.menu.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("menu")
public class MenuController {
    @Autowired
    private RoleMenuService roleMenuService;

    @RequestMapping("getMenus")
    public Result getMenus(HttpServletRequest request) {
        String token = request.getHeader("token");
        Integer uid = (Integer) JWTUtil.parseToken(token).getPayload("id");
        System.out.println("当前登录用户id" + uid);

        ArrayList<Menu> nodeList = roleMenuService.getMenus(uid);
        System.out.println("当前登陆者所有菜单" + nodeList);
        //配置
        TreeNodeConfig treeNodeConfig = new TreeNodeConfig();
//转换器 (含义:找出父节点为字符串零的所有子节点, 并递归查找对应的子节点, 深度最多为 3)
        List<Tree<String>> treeNodes = TreeUtil.build(nodeList, "0", treeNodeConfig,
                (treeNode, tree) -> {
                    tree.setId(treeNode.getId() + "");
                    tree.setParentId(treeNode.getPersonId() + "");
                    tree.setName(treeNode.getName());
                    // 扩展属性 ...
                    tree.putExtra("path", treeNode.getPath());
                    tree.putExtra("component", treeNode.getComponent());
                });

        return Result.success(treeNodes);
    }
}
